package com.king.hessian;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;

import com.caucho.hessian.client.HessianConnection;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用httpClient访问rpc server
 */
@Slf4j
public class HttpClientHessianConnection implements HessianConnection {

    private HttpClient httpClient;

    private HttpPost httpPost;

    private ByteArrayOutputStream outputStream;

    private int statusCode = -1;

    private String statusMessage = null;

    private HttpResponse httpResponse;

    public HttpClientHessianConnection(HttpClient httpClient, URL url) {
        this.httpClient = httpClient;
        this.httpPost = new HttpPost(url.toExternalForm());
        this.outputStream = new ByteArrayOutputStream();
    }


    @Override
    public void addHeader(String name, String value) {
        httpPost.addHeader(name, value);
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return outputStream;
    }

    @Override
    public void sendRequest() throws IOException {
        byte[] bytes = outputStream.toByteArray();
        if (log.isDebugEnabled()) {
            log.debug("hessian request entity size = " + bytes.length);
        }
        HttpEntity httpEntity = new ByteArrayEntity(bytes);
        httpPost.setEntity(httpEntity);
        httpResponse = httpClient.execute(httpPost);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        statusMessage = httpResponse.getStatusLine().getReasonPhrase();
    }

    @Override
    public int getStatusCode() {
        return statusCode;
    }

    @Override
    public String getStatusMessage() {
        return statusMessage;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return httpResponse.getEntity().getContent();
    }

    @Override
    public void close() throws IOException {
    }

    @Override
    public void destroy() throws IOException {
    }
}
